package util

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
)

func Post(url string, param map[string]interface{}) ([]byte, error) {
	// 目标URL
	//url := "http://example.com/post"
	// 要发送的数据
	//data := `{"key1":"value1", "key2":"value2"}`
	// 将数据转换为字节切片
	//payload := bytes.NewBufferString(data)

	data, _ := json.Marshal(param)
	dataString := string(data)
	payload := bytes.NewBufferString(dataString)

	// 发送POST请求
	resp, err := http.Post(url, "application/json", payload)
	if err != nil {
		log.Fatalf("Error sending POST request: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}
	return body, err
}

func Get(url string, param map[string]interface{}) ([]byte, error) {
	targetUrl := url
	if len(param) > 0 {
		targetUrl += "?"
		for k, v := range param {
			data := fmt.Sprintf("%v=%v&", k, v) //data = userName=111&
			targetUrl = fmt.Sprintf("%s%s", targetUrl, data)
		}
	}

	//移除尾部字符
	targetUrl = targetUrl[:len(targetUrl)-1]
	fmt.Println(targetUrl)

	// 发送POST请求
	resp, err := http.Get(targetUrl)
	if err != nil {
		log.Fatalf("Error sending Get request: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}
	return body, err
}
